package com.greate.community.jwt;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.greate.community.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Data
public class JwtUser implements UserDetails {

    private Integer id;

    private String username;

    @JsonIgnore
    private String password;

    private Integer status;

    private Collection<? extends GrantedAuthority> authorities;

    public JwtUser() {
    }

    public JwtUser(Integer id, String username, String password, Integer status, Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.status = status;
        this.authorities = authorities;
    }

    public static JwtUser build(User user) {
        List<GrantedAuthority> authorities = null;
        return new JwtUser(user.getId(), user.getUsername(), user.getPassword(), user.getStatus(), authorities);
    }

    public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    //账户是否过期,过期无法验证
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //指定用户是否被锁定或者解锁,锁定的用户无法进行身份验证, 0.禁用 1.正常 2.被删除
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        if (status == null) {
            return false;
        }
        return status==1;
    }

    //指示是否已过期的用户的凭据(密码),过期的凭据防止认证
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //是否被禁用,禁用的用户不能身份验证
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
